<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>新增栏目</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>

</head>
<body>

<form class="layui-form" action="" id="layui-form">
    <div class="mainBox">
        <div class="main-container">
            <!-- 栏目名称 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目名称</label>
                <div class="layui-input-block">
                    <input type="text" name="channelName" required lay-verify="required|checkChannelName"
                           placeholder="请输入栏目名称" class="layui-input" maxlength="100" id="channelName">
                    <div id="titleCharCount" class="char-count">0/100</div>
                </div>
            </div>
            <!-- 父级栏目 (树形选择) -->
            <div class="layui-form-item">
                <label class="layui-form-label">父级栏目</label>
                <div class="layui-input-block">
                    <input type="text" id="parent-tree-input" placeholder="请选择父级栏目" class="layui-input"
                           readonly="readonly">
                    <!-- 清空按钮 -->
                    <button type="button" id="clear-parent" class="layui-btn  layui-btn-sm"
                            style="position: absolute; right: 5px; top: 5px;">
                        清空
                    </button>
                    <!-- 用于提交的隐藏字段 -->
                    <input type="hidden" name="parentId" id="parentName"/>
                    <div id="parent-tree"
                         style="display:none; position: absolute; z-index: 1000; background-color: #fff; border: 1px solid #d2d2d2; width: 100%; max-height: 300px; overflow-y: auto;"></div>
                </div>
            </div>
            <!-- 栏目排序 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目排序</label>
                <div class="layui-input-block">
                    <input type="number" min="0" max="65535" name="channelSort" placeholder="请输入栏目排序"
                           class="layui-input"
                           id="channelSort" lay-verify="required">
                </div>
            </div>
            <!-- 栏目路径 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目路径</label>
                <div class="layui-input-block">
                    <input type="text" name="urlKey" placeholder="请输入栏目路径" class="layui-input"
                           id="urlKey" maxlength="50" lay-verify="required|checkUrlKey">
                    <div id="urlKeyCharCount" class="char-count">0/50</div>
                </div>
            </div>
            <!-- 模版类型 -->
            <div class="layui-form-item">
                <label class="layui-form-label">模板类型</label>
                <div class="layui-input-block" style="display: flex;justify-content: flex-start">
                    <div class="layui-col-md4">
                        <select id="selectType" name="type" lay-verify="required" lay-filter="templateType">
                            <option value="">请选择模板类型</option>
                        </select>
                    </div>
                    <div class="layui-col-md4" style="display:none;" id="templateWrapper">
                        <select id="selectTemplate" name="templateId" lay-filter="template">
                            <option value="">请选择模板</option>
                        </select>
                    </div>
                    <div class="layui-col-md4" style="display:none;" id="infoWrapper">
                        <select id="selectInfo" name="detailTemplate" lay-filter="info">
                            <option value="">请选择文章详细页</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否审核</label>
                <div class="layui-input-block">
                    <input type="radio" name="isChecked" value="1" title="是" checked>
                    <input type="radio" name="isChecked" value="2" title="否">
                </div>
            </div>
            <div class="layui-form-item" id="channelStruct" style="display: none">
                <label class="layui-form-label">栏目结构</label>
                <div class="layui-input-block">
                    <select id="selectStruct" name="structId" lay-filter="struct">
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-success" lay-submit=""
                    lay-filter="add-channel">
                <i class="layui-icon layui-icon-ok"></i>
                保存
            </button>
            <button type="reset" class="layui-btn layui-btn-danger">
                <i class="layui-icon layui-icon-delete"></i>
                取消
            </button>
        </div>
    </div>
</form>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'tree', 'jquery'], function () {
        let form = layui.form;
        let tree = layui.tree;
        let $ = layui.jquery;
        let baseURL = /*[[@{/}]]*/ '';
        // 在页面加载时加载初始的 select 选项
        $.ajax({
            url: baseURL + "cms/struct/getStructList",
            type: 'get',
            success: function (res) {
                let select = $('#selectStruct');
                select.empty().append('<option value="0">请选择栏目结构</option>'); // 清空现有的选项
                res.data.forEach(function (option) {
                    select.append('<option value="' + option.structId + '">' + option.name + '</option>');
                });
                form.render('select'); // 重新渲染 select 元素
            }
        });
        //表单验证
        form.verify({
            checkChannelName: function (value) {
                if (!new RegExp("^[a-zA-Z\\u4e00-\\u9fa5][a-zA-Z0-9\\u4e00-\\u9fa5\\s]*$").test(value)) {
                    return '栏目名称不能包含特殊字符，且不能以数字开头';
                }
            },
            checkUrlKey: function (value) {
                if (!new RegExp("^[a-zA-Z0-9]+$").test(value)) {
                    return '栏目路径只能包含字母和数字';
                }
            }
        });
        $('#channelName').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#titleCharCount').text(currentLength + "/" + maxLength);
        });
        $('#urlKey').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#urlKeyCharCount').text(currentLength + "/" + maxLength);
        });


        // 初始化树形结构的隐藏状态
        $('#parent-tree').hide();


        // 点击输入框时显示树形结构
        $('#parent-tree-input').on('click', function () {
            $('#parent-tree').toggle(); // 显示或隐藏树形结构
        });

        // 渲染父级栏目树形结构
        $.get(baseURL + "cms/channel/getParentMenus", function (data) {
            tree.render({
                elem: '#parent-tree', // 树形组件容器
                data: data, // 后端返回的树形数据
                click: function (obj) {
                    if (obj && obj.data) {
                        $('#parent-tree-input').val(obj.data.title); // 填充栏目名称
                        $('#parentName').val(obj.data.id); // 填充栏目ID
                        $('#parent-tree').hide(); // 隐藏树形选择框
                    } else {
                        console.error("无法获取节点数据");
                    }
                }
            });
        });

        // 点击清空按钮时，清空输入框和隐藏树形结构
        $('#clear-parent').on('click', function () {
            $('#parent-tree-input').val(''); // 清空输入框
            $('#parentName').val(''); // 清空隐藏的父级ID
            $('#parent-tree').hide(); // 隐藏树形结构
        });
        // 点击空白区域时，关闭树形选择框
        $(document).on('click', function (e) {
            if (!$(e.target).closest('#parent-tree-input').length && !$(e.target).closest('#parent-tree').length) {
                $('#parent-tree').hide();
            }
        });

        //模板类型下拉框
        let typeList = null
        $.ajax({
            url: baseURL + "cms/template/getTemplateTypeList",
            type: 'GET',
            success: function (res) {
                if (res.code === 1000) {
                    typeList = res.data
                    let dropdownData = res.data.map(item => {
                        return {
                            "id": item.templateTypeId,
                            "title": item.typeName
                        };
                    });
                    let selectElem = $('#selectType'); // 下拉框的容器
                    selectElem.empty();  // 清空下拉框内容
                    selectElem.append('<option value="">请选择模板内容</option>');
                    dropdownData.forEach(item => {
                        selectElem.append(`<option value="${item.id}">${item.title}</option>`);
                    });
                    form.render('select');
                }
            },
            error: function (xhr, status, error) {
                console.error(error);
            }
        })

        //文章详细列表下拉框
        function loadInfo(type) {
            let infoSelect = $('#selectInfo');
            infoSelect.empty(); // 清空模板内容下拉框
            $('#infoWrapper').hide(); // 隐藏模板内容选择框
            $('#selectInfo').removeAttr('lay-verify');  // 移除验证
            let t = typeList.find(item => {
                if (item.code == "LIST" && item.templateTypeId == type) {
                    return item;
                }
            });
            if (t) {
                infoSelect.append('<option value="">请选择文章详细页内容</option>');
                $.ajax({
                    url: baseURL + "cms/template/getDetailList",
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 1000) {
                            res.data.forEach(item => {
                                infoSelect.append(`<option value="${item.templateId}">${item.templateName}</option>`);
                            });
                            // 显示模板内容下拉框
                            $('#infoWrapper').show();
                            $('#selectInfo').attr('lay-verify', 'required');  // 添加验证
                            form.render('select'); // 渲染模板内容下拉框
                        }
                    }, error: function (xhr, status, error) {
                        console.error(error);
                    }
                });
            }
        }

        //下拉框的动态显示
        form.on('select(templateType)', function (data) {
            let selectedTemplateTypeId = data.value;
            console.log(selectedTemplateTypeId)
            // 清空模板内容下拉框并隐藏
            let templateSelect = $('#selectTemplate');
            templateSelect.empty();
            $('#templateWrapper').hide();
            $('#selectTemplate').removeAttr('lay-verify');
            let infoSelect = $('#selectInfo');
            infoSelect.empty();
            $('#infoWrapper').hide();
            $('#selectInfo').removeAttr('lay-verify');
            if (selectedTemplateTypeId === '10' || selectedTemplateTypeId === '13') {
                $('#channelStruct').show() // 使用 jQuery 的 css 方法
            } else {
                $('#channelStruct').hide(); // 确保隐藏
            }// 移除验证
            if (selectedTemplateTypeId) {
                $.ajax({
                    url: baseURL + "cms/template/getListByTypeId", // 假设接口返回对应模板内容数据
                    type: 'GET',
                    data: {templateTypeId: selectedTemplateTypeId}, // 传递模板类型ID
                    success: function (res) {
                        if (res.code === 1000) {
                            templateSelect.append('<option value="">请选择模板内容</option>');
                            res.data.forEach(item => {
                                templateSelect.append(`<option value="${item.templateId}">${item.templateName}</option>`);
                            });
                            // 显示模板内容下拉框并渲染
                            $('#templateWrapper').show();
                            $('#selectTemplate').attr('lay-verify', 'required');
                            form.render('select'); // 重新渲染模板内容下拉框
                            loadInfo(selectedTemplateTypeId)
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error(error);
                    }
                });
            }
        });


        // 表单提交事件
        form.on('submit(add-channel)', function (data) {
            console.log(data.field)
            let loading = layer.msg('正在提交中...', {
                icon: 16,
                shade: 0.3,
                time: false
            });
            $.ajax({
                url: baseURL + 'cms/channel/add',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        $.ajax({
                            url: baseURL + "config",
                            type: 'get',
                            success: function (param) {
                                // 发送消息到父页面
                                window.parent.parent.postMessage({
                                    type: 'updateMenu',
                                    data: param
                                }, '*');
                            }
                        })
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name)); // 关闭当前窗口
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false;
        });
    });
</script>
</body>
</html>
